using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Framework.DataTable
{
    public class DataTableConfigTsv : DataTableConfigBase
    {
        protected string[] defDeine;
        protected string[] defName;
        protected string[] defType;
        protected string[] defComment;

        protected int fieldCount;
        protected List<string> _tempValueList = new List<string>();
        protected StringBuilder _builder = new StringBuilder();
        protected List<string> _dataLineList = new List<string>();
        public override void ReadFile(string path)
        {
            base.ReadFile(path);
            var lines = File.ReadAllLines(path, Encoding.GetEncoding("gb2312"));
            var list = new List<string>();
            list.AddRange(lines);
            parseLines(list);
        }
        protected void parseLines(List<string> lines)
        {
            var len = lines.Count;
            var defList = new List<string>();
            var nameList = new List<string>();
            var typeList = new List<string>();
            var commentList = new List<string>();
            for (int i = 0; i < len; i++)
            {
                var line = lines[i];
                //if (string.IsNullOrEmpty(line.Trim()))
                //{
                //    continue;
                //}
                if (line.StartsWith("#"))
                {
                    if (line.StartsWith("#define"))
                    {
                        _tempValueList.Clear();
                        _tempValueList.AddRange(line.Split("\t".ToCharArray()));
                        for (int j = 1; j < _tempValueList.Count; j++) { defList.Add(_tempValueList[j]); }
                    }
                    else if (line.StartsWith("#name"))
                    {
                        _tempValueList.Clear();
                        _tempValueList.AddRange(line.Split("\t".ToCharArray()));
                        for (int j = 1; j < _tempValueList.Count; j++) { nameList.Add(_tempValueList[j]); }
                    }
                    else if (line.StartsWith("#type"))
                    {
                        _tempValueList.Clear();
                        _tempValueList.AddRange(line.Split("\t".ToCharArray()));
                        for (int j = 1; j < _tempValueList.Count; j++) { typeList.Add(_tempValueList[j]); }
                    }
                    else if (line.StartsWith("#comment"))
                    {
                        _tempValueList.Clear();
                        _tempValueList.AddRange(line.Split("\t".ToCharArray()));
                        for (int j = 1; j < _tempValueList.Count; j++) { commentList.Add(_tempValueList[j]); }
                    }
                    continue;
                }
                _dataLineList.Add(line);
            }
            fieldCount = nameList.Count;
            defDeine = new string[fieldCount];
            defName = new string[fieldCount];
            defType = new string[fieldCount];
            defComment = new string[fieldCount];
            for (int j = 0; j < fieldCount; j++)
            {
                var nameValue = nameList[j];
                var name = nameValue;
                var type = j >= typeList.Count ? string.Empty : typeList[j];
                var splitId = nameValue.IndexOf(":");
                if (splitId > 0)
                {
                    name = nameValue.Substring(0, splitId);
                    if (string.IsNullOrEmpty(type))
                    {
                        type = nameValue.Substring(splitId + 1);
                    }
                }
                defDeine[j] = j >= defList.Count ? string.Empty : defList[j];
                defName[j] = name;
                defType[j] = type;
                defComment[j] = j >= commentList.Count ? "" : commentList[j];
            }
            parse();
        }
        private void parse()
        {
            if (defName == null)
            {
                this.Enabled = false;
                FrameworkLog.LogError("没有定义字段名 #name");
                return;
            }
            else if (defType == null)
            {
                this.Enabled = false;
                FrameworkLog.LogError("没有定义字段类型 #type");
                return;
            }
            for (var i = 0; i < fieldCount; i++)
            {
                var name = Utils.Text.FirstCharUpper(defName[i].Replace(" ", ""));
                var type = defType[i].Replace(" ", "");
                var def = string.Empty;
                var comment = defComment[i];
                if (defDeine != null)
                {
                    def = defDeine[i].Trim();
                }
                if (!Header.AddFieldInfo(name, type, def, i, comment))
                {
                    FrameworkLog.LogErrorFormat("添加字段出错 name:{0},type:{1},define:{2}", name, type, def);
                    this.Enabled = false;
                    return;
                }
                // Debug.LogError(name + " " + type + " " + def + " " + (i - 1));
            }
            DataInfos = new List<string[]>();
            _builder.Clear();
            _tempValueList.Clear();
            var index = 0;
            var count = _dataLineList.Count;
            char splitValue = '\t';
            string str;

            while (count-- > 0)
            {
                var line = _dataLineList[index++];
                var fid = line.IndexOf(splitValue);
                if (fid >= 0)
                {
                    //清除第一列数据
                    line = "" + splitValue + line.Substring(fid + 1);
                }
                if (line.Length < 1)
                {
                    if (_tempValueList.Count > 0)
                    {
                        _builder.Append("\\n");
                    }
                    continue;
                }
                var len = line.Length;
                bool append = false;
                for (var i = 0; i < len; i++)
                {
                    var c = line[i];

                    if (c.Equals(splitValue))
                    {
                        str = _builder.ToString();
                        try
                        {
                            str = formatItem(str);
                        }
                        catch (System.Exception)
                        {

                            throw;
                        }

                        _tempValueList.Add(str);
                        if (_tempValueList.Count >= fieldCount + 1)
                        {
                            addLine();
                            _tempValueList.Clear();
                            _tempValueList.Add(string.Empty);

                        }
                        _builder.Clear();
                        append = false;
                    }
                    else
                    {
                        _builder.Append(c);
                        append = true;
                    }
                }
                if (append && _tempValueList.Count < fieldCount)
                {
                    _builder.Append("\\n");
                }
            }
            str = _builder.ToString();
            str = formatItem(str);
            _tempValueList.Add(str);
            if (_tempValueList.Count >= fieldCount + 1)
            {
                addLine();
                _tempValueList.Clear();
            }
            this.Enabled = DataInfos.Count > 0;
        }
        private void addLine()
        {
            var lineValue = new string[fieldCount];
            _tempValueList.CopyTo(1, lineValue, 0, fieldCount);
            _tempValueList.Clear();
            if (Header.IndexField != null)
            {
                if (string.IsNullOrEmpty(lineValue[Header.IndexField.DeclarIndex]))
                {
                    return;
                }
            }
            int count = fieldCount;
            var dataCount = count;
            for (var i = 0; i < count; i++)
            {
                if (string.IsNullOrEmpty(lineValue[i].Trim()))
                {
                    dataCount--;
                }
            }
            if (dataCount < 1)
            {
                return;
            }
            DataInfos.Add(lineValue);
        }
        private string formatItem(string value)
        {
            var item = value.Trim();
            if (item.Length < 2)
            {
                return item;
            }
            if (item.StartsWith("\"") && item.EndsWith("\""))
            {
                item = item.Substring(1, item.Length - 2);
                item = item.Replace("\"\"", "\"");
            }
            return item;
        }
    }
}